//
//  LoginUtil.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 12.04.25.
//

import Foundation
import CommonCrypto

import Foundation
import CommonCrypto

class LoginUtils {
    static private let key = "rkKbcCa3nxY8YwAWUpu2PwUcMgSFwL2r".data(using: .utf8)! // 32 字节密钥
    static private let iv = "BYfmvhVjpPwUcMgS".data(using: .utf8)! // 16 字节 IV
    
    static func encrypt(pwd: String) -> String {
        do {
            let dataToEncrypt = pwd.data(using: .utf8)!
            let encryptedData = try AESUtils.encrypt(data: dataToEncrypt, key: key, iv: iv)
            return encryptedData.base64EncodedString()
        } catch {
            return "encrypt_error"
        }
    }
}


func aesExample() {
    let key = "rkKbcCa3nxY8YwAWUpu2PwUcMgSFwL2r".data(using: .utf8)! // 32 字节密钥
    let iv = "BYfmvhVjpPwUcMgS".data(using: .utf8)! // 16 字节 IV

    let originalText = "18500540902"
    let dataToEncrypt = originalText.data(using: .utf8)!

    do {
        // 加密
        let encryptedData = try AESUtils.encrypt(data: dataToEncrypt, key: key, iv: iv)
        print("加密后的数据 (Base64):", encryptedData.base64EncodedString())

        // 解密
        let decryptedData = try AESUtils.decrypt(data: encryptedData, key: key, iv: iv)
        let decryptedText = String(data: decryptedData, encoding: .utf8)!
        print("解密后的文本:", decryptedText)
    } catch {
        print("错误:", error)
    }
}

class AESUtils {

    static func encrypt(data: Data, key: Data, iv: Data) throws -> Data {
        return try crypt(input: data, key: key, iv: iv, operation: CCOperation(kCCEncrypt))
    }

    static func decrypt(data: Data, key: Data, iv: Data) throws -> Data {
        return try crypt(input: data, key: key, iv: iv, operation: CCOperation(kCCDecrypt))
    }

    private static func crypt(input: Data, key: Data, iv: Data, operation: CCOperation) throws -> Data {
        // 检查密钥和 IV 的长度
        guard key.count == kCCKeySizeAES256 else {
            throw NSError(domain: "AES", code: -1, userInfo: [NSLocalizedDescriptionKey: "密钥长度无效"])
        }
        guard iv.count == kCCBlockSizeAES128 else {
            throw NSError(domain: "AES", code: -1, userInfo: [NSLocalizedDescriptionKey: "IV 长度无效"])
        }

        // 创建输出缓冲区
        var outLength = Int(0)
        let outputBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: input.count + kCCBlockSizeAES128)
        defer { outputBuffer.deallocate() } // 确保内存被释放

        let status = input.withUnsafeBytes { inputBytes in
            key.withUnsafeBytes { keyBytes in
                iv.withUnsafeBytes { ivBytes in
                    CCCrypt(
                        operation,                     // 加密或解密
                        CCAlgorithm(kCCAlgorithmAES),  // AES 算法
                        CCOptions(kCCOptionPKCS7Padding), // PKCS7 填充
                        keyBytes.baseAddress,          // 密钥
                        key.count,                     // 密钥长度
                        ivBytes.baseAddress,           // IV
                        inputBytes.baseAddress,        // 输入数据
                        input.count,                   // 输入数据长度
                        outputBuffer,                  // 输出缓冲区
                        input.count + kCCBlockSizeAES128, // 输出缓冲区大小
                        &outLength                     // 输出数据实际长度
                    )
                }
            }
        }

        guard status == kCCSuccess else {
            throw NSError(domain: "AES", code: Int(status), userInfo: [NSLocalizedDescriptionKey: "AES 操作失败"])
        }

        return Data(bytes: outputBuffer, count: outLength)
    }
}
